package com.project.common.xss;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringEscapeUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Description: Html
 * @Author: zhuchi
 * @CreateDate: 2020/7/22 18:29
 * @Version: 1.0
 */
public class XssAndSqlHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private HttpServletRequest request;

    public XssAndSqlHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
        this.request = request;
    }

    @Override
    public String getParameter(String name)
    {
        String value = request.getParameter(name);
        if (!StringUtils.isEmpty(value))
        {
            value = StringEscapeUtils.escapeHtml4(value);
        }
        return value;
    }


    @Override
    public String[] getParameterValues(String name)
    {
        String[] parameterValues = super.getParameterValues(name);
        if (parameterValues == null)
        {
            return null;
        }
        for (int i = 0; i < parameterValues.length; ++i)
        {
            String value = parameterValues[i];
            parameterValues[i] = StringEscapeUtils.escapeHtml4(value);
        }
        return parameterValues;
    }

    @Override
    public Map<String,String[]> getParameterMap() {
        Map<String,String[]> map = new LinkedHashMap<>();
        Map<String,String[]> parameters = super.getParameterMap();
        for (String key : parameters.keySet()) {
            String[] values = parameters.get(key);
            for (int i = 0; i < values.length; i++) {
                values[i] = StringEscapeUtils.escapeHtml4(values[i]);
            }
            map.put(key, values);
        }
        return map;
    }


}
